package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author tongchen
 * @create 2023-02-20 10:50
 */
public class TcpEchoService {
    //通过创建构造方法指定端口号获取socket连接
    private ServerSocket socket;

    public TcpEchoService(int port) throws IOException {
        //判断端口的有效性
        if(port<1025||port>65535){
            throw new BindException("端口建议在1025和65535之间.......");
        }
        //通过指定端口号创建socket服务
        this.socket=new ServerSocket(port);
    }

    //获取客户端连接
    public void start() throws IOException {
        System.out.println("服务端端获取连接成功......");
        //不断循环接收用户的请求
        while(true){
            //获取与客户端的连接
            Socket clientSocket = socket.accept();
           //处理用户请求
            pocessRequset(clientSocket);

        }

    }

    private void pocessRequset(Socket clientSocket) throws IOException {
        //打印客户端信息
        System.out.printf("%s|%d,客服端连接成功......\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        //通过clientSocket中获取输入和输出数据
        try(InputStream inputStream=clientSocket.getInputStream(); OutputStream outputStream=clientSocket.getOutputStream()){
            //循环从输入中获取数据
            while (true){
                Scanner scan=new Scanner(inputStream);
                //判断是否存在
                if(!scan.hasNextLine()){
                    System.out.printf("%s|%d,客服端退出成功......",clientSocket.getInetAddress().toString(),clientSocket.getPort());
                    break;
                }
                //获取数据并获得返回数据
                String request=scan.nextLine();
                String response=pocess(request);
                //发送数据
                PrintWriter printWriter = new PrintWriter(outputStream);
                //注意输入输出格式的一致性（用户和客户端）
                printWriter.println(response);
                //强制刷新缓存区
                printWriter.flush();
                //打印信息
                System.out.printf("[%s:%d] request = %s, response = %s\n", clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(), request, response);

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            clientSocket.close();

        }
    }

    private String pocess(String request) {
        return request;
    }
    //初始化服务器
    public static void main(String[] args) throws IOException {
        TcpEchoService tcpEchoService = new TcpEchoService(9090);
        tcpEchoService.start();
    }

}
